package com.lagou.service.impl;

import com.lagou.dao.LagouAuthCodeDao;
import com.lagou.pojo.LagouAuthCode;
import com.lagou.service.CodeService;
import com.lagou.service.MailService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;

/**
 * @Author : liuchangling
 * @Descrition :
 * @Date： Created in 4:20 下午 2022/1/31
 */
@Service
public class CodeServiceImpl implements CodeService {
    private Random random = new Random();
    private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private LagouAuthCodeDao lagouAuthCodeDao;

    @Reference
    private MailService mailService;


    @Override
    public boolean createCode(String email) {
        LagouAuthCode lagouAuthCode=new LagouAuthCode();
        lagouAuthCode.setEmail(email);
        //创建6位随机数 int number = (int)(Math.random()*(maxNumber-minNumber+1)+minNumber);
        int number = (int)(Math.random()*(999999-100000+1)+100000);
        lagouAuthCode.setCode(number+"");
        LocalDateTime createTime=LocalDateTime.now();

        lagouAuthCode.setCreateTime(formatter.format(createTime));
        //设置一分钟后过期
        lagouAuthCode.setExpireTime(formatter.format(createTime.plusMinutes(1)));
        lagouAuthCodeDao.save(lagouAuthCode);
        return mailService.sendMail(email,number+"");
    }

    @Override
    public Integer validateCode(String email, String code) {
        System.out.println("邮箱："+email);
        System.out.println("验证码："+code);
        List<LagouAuthCode> list=lagouAuthCodeDao.findByEmailAndCode(email,code);
        if(CollectionUtils.isEmpty(list)){
            System.out.println("未查询到该验证码");
            return 1;
        }
        LagouAuthCode lagouAuthCode = list.get(list.size() - 1);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime expireTime = LocalDateTime.parse(lagouAuthCode.getExpireTime(),df);
        if(expireTime.isBefore(LocalDateTime.now())){
            System.out.println("验证码超时");
            return 2;
        }
        return 0;
    }


}
